package com.wxhandle.cleandemo.core.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtil {
    private static ObjectMapper mapper = new ObjectMapper(); 

    public static String beanToJson(Object bean) throws JsonProcessingException{
        return mapper.writeValueAsString(bean);
    }

    public static <T> T jsonToBean(String json, Class<T> classOfT) throws JsonParseException, JsonMappingException, IOException{
        return mapper.readValue(json, classOfT);
    }

    public static <T> T jsonToBean(String json, TypeReference<T> valueTypeRef) throws JsonParseException, JsonMappingException, IOException{
        return mapper.readValue(json, valueTypeRef);
    }

    public static <T> T fileToBean(File  file, TypeReference<T> valueTypeRef) {
        InputStream fis;
        if (file.exists()){
            fis = null;
            try {
                fis = new FileInputStream(file);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            try {
                InputStreamReader isr = new InputStreamReader(fis);
                BufferedReader br = new BufferedReader(isr);
                String line;
                StringBuilder sb = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    sb.append(line);
                }
                br.close();
                isr.close();
                fis.close();
                fis = null;
                return jsonToBean(sb.toString(), valueTypeRef);
            } catch (Exception e) {
            }
        }
        return null;
    }
}
